<template>
  <div class="page-table">
    <div class="page-filter">
      <div class="query">
        <el-form ref="form" :inline="true" size="small">
          <el-form-item label="出发地" prop="startCode">
            <ad-city-select v-model="startCode"/>
          </el-form-item>
          <el-form-item label="目的地" prop="destinationCode">
            <ad-city-select v-model="destinationCode"/>
          </el-form-item>
          <el-button type="primary" plain size="small" @click="queryList()">价格查询
          </el-button>
        </el-form>
      </div>
      <div class="op">
        <el-button type="success" v-permission="['price:export']" v-show="!showDetailed" size="mini" @click="downExcelTemp('价格库模板.xlsx')">下载模板</el-button>
        <el-button size="mini" v-permission="['price:import']" v-show="!showDetailed" type="primary" plain @click.native="batchImport">导入</el-button>
        <el-button size="mini" v-show="!showDetailed" v-permission="['price:export']" type="primary" plain @click="exportExcel">导出</el-button>
        <el-button size="mini" v-permission="['price:add']" v-show="!showDetailed" type="primary" plain @click="addPrice">新增</el-button>
        <el-button size="mini" v-show="showDetailed" type="primary" plain @click="showDetailed=false">返回</el-button>
      </div>
    </div>
    <div v-if="showDetailed">
      <detailed ref="detailed" :startCode="startCode" :destinationCode="destinationCode"/>
    </div>
    <ad-table v-else ref="order" :show-summary="orderSummary"
              :data="orderList" v-loading="orderInitLoading" border u-table
              :data-changes-scroll-top="orderIsScrollTop" @table-body-scroll="orderGetMoreList"
              @row-click="orderSelectRow" @selection-change="orderSelectRows"
              :searchQuery="orderSearchQuery" @search="orderGetInitList"
              @sort-change="orderSortInitList" @filter-change="orderFilterInitList" :height="tableHeight">
      <ad-table-column label="序号" type="index" ctype="index" fixed/>
      <u-table-column label="中转次数" prop="settlementTime" width="80">
        <template v-slot="{row}">
          <span>直达</span>
        </template>
      </u-table-column>
      <ad-table-column label="出发地" prop="startCode" queryPro="startName" ctype="city" searchable/>
      <ad-table-column label="目的地" prop="destinationCode" queryPro="destinationName" ctype="city" searchable/>
      <ad-table-column label="参考报价" prop="totalFee" width="100" sortable/>
      <ad-table-column label="利润" prop="profit" width="100" sortable/>
      <ad-table-column label="运输时效" prop="days" width="100" sortable/>
      <ad-table-column label="承运成本" prop="cost" width="100" sortable/>
      <ad-table-column label="供应商" prop="companyName" w="3c2f" searchable/>
      <ad-table-column label="网点城市" prop="siteName" w="3c2f" searchable/>
      <ad-table-column label="联系人" prop="linkman" w="3c2f" searchable/>
      <ad-table-column label="联系电话" prop="linkPhone" ctype="phone-2f" searchable/>
      <u-table-column label="提车费" prop="settlementUser" width="240">
        <template v-slot="{row}">
          <div style="position: absolute;top:2px;left:2px">
            <ad-select @change="getPickCost(row,row.$index)" size="mini" style="width: 90px" placeholder="区"
                       v-model="row.pickAreaCode" :options="row.startAreaList"
                       :config="{optionKey: 'name', optionValue: 'code'}"/>
            <el-select @change="getPickCost(row,row.$index)" clearable size="mini" style="width: 90px;margin-left: 2px"
                       v-model="row.pickType"
                       placeholder="类型">
              <el-option :key="'t1'" :label="'人工提'" :value="1"></el-option>
              <el-option :key="'t2'" :label="'小板提'" :value="2"></el-option>
            </el-select>
            <span style="margin-left: 10px">{{row.pickFee ? row.pickFee: '-'}}</span>
          </div>
        </template>
      </u-table-column>
      <u-table-column label="送车费" prop="settlementUser" width="240">
        <template v-slot="{row}">
          <div style="position: absolute;top:2px;left:2px">
            <ad-select @change="getTakeCost(row)" size="mini" style="width: 90px" placeholder="区"
                       v-model="row.takeAreaCode" :options="row.destinationAreaList"
                       :config="{optionKey: 'name', optionValue: 'code'}"/>
            <el-select @change="getTakeCost(row)" clearable size="mini" style="width: 90px;margin-left: 2px"
                       v-model="row.takeType"
                       placeholder="类型">
              <el-option :key="'t1'" :label="'人工送'" :value="1"></el-option>
              <el-option :key="'t2'" :label="'小板送'" :value="2"></el-option>
            </el-select>
            <span style="margin-left: 10px">{{row.takeFee ? row.takeFee: '-'}}</span>
          </div>
        </template>
      </u-table-column>
      <ad-table-column label="添加人" prop="createUserName" w="3c2f" searchable/>
      <ad-table-column label="更新时间" prop="updateTime" ctype="datetime" sortable/>
      <ad-table-column label="审核人" prop="checkUserName" w="3c2f" searchable/>
      <ad-table-column label="审核时间" prop="checkTime" ctype="datetime" sortable/>
      <ad-table-column label="备注" prop="remark" width="200"/>
      <ad-table-column label="操作" fixed="right" width="50">
        <template v-slot="{row}">
          <div class="op">
            <el-button type="text" class="op-btn" @click="openOrderAdder(row)">修改</el-button>
          </div>
        </template>
      </ad-table-column>
    </ad-table>

    <el-dialog :title="titleName" :visible.sync="orderAdder.visible" custom-class="ad-dialog" width="600px">
      <adder :mode="orderAdder.mode" :id="orderSelectedRowId" :visible.sync="orderAdder.visible" @saved="orderSaved"/>
    </el-dialog>
    <!--批量导入模板-->
    <el-dialog :show-close="false" title="导入" width="500px" :visible.sync="batchImportVisible"
               :close-on-click-modal="false">
      <el-form ref="batchImportForm" :model="batchImportForm" label-width="130px" size="small">
        <!--        <el-progress :text-inside="true" :stroke-width="18" v-show="progressShow" :percentage="progressNum"-->
        <!--                     status="success" style="margin-bottom:10px;"></el-progress>-->
        <div class="ad-block">
          <el-upload
              class="avatar-uploader"
              accept=".xlsx,.xls"
              ref="uploadFile"
              :headers="headers"
              :auto-upload="false"
              :action="url+'api/price-library/import-excel'"
              :on-success="onSuccess"
              :on-change="fileChange"
              :file-list="fileList"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
          >
            <el-button :disabled="isExcel" slot="trigger" size="small" type="primary">选择EXCEL</el-button>
            <el-input v-model="this.batchImportForm.fileName" size="small" style="width:230px;"
                      :readonly="true"></el-input>
            <el-button :disabled="isExcel" size="small" type="success" @click="uploadExcel">导入文件</el-button>
          </el-upload>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="batchImportVisible = false" size="small">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import AdTable from '@/components/AdTable'
  import AdTableColumn from '@/components/AdTable/AdTableColumn'
  import AdCitySelect from '@/components/AdCitySelect'
  import adder from './add'
  import Detailed from './Detailed'
  import adTable from '@/mixins/adTable/index'
  import AdSelect from '@/components/AdSelect'
  import api, {getList as orderApiGetList} from '@/api/price'
  import {download} from '@/api/data'
  import {downloadFile} from '@/utils/index'
  import {getToken} from '@/utils/auth'
  import moment from 'moment'

  export default {
    name: 'price-price',
    components: {AdSelect, AdTable, AdTableColumn, AdCitySelect, adder, Detailed},
    dicts: ['finance_type', 'finance_customer_subject', 'finance_channel'],
    mixins: [adTable('order')],
    data() {
      return {
        startCode: null,
        destinationCode: null,
        tableHeight: document.documentElement.clientHeight - 140,
        dialogVisible: false,
        showDetailed: false,
        infoForm: {
          type: null,
          customerSubject: null,
          settlementUser: null,
          settlementTime: null,
          createUser: null,
          createTime: null,
          collectionFee: null,
          paymentFee: null,
          balanceFee: null,
          channel: null,
          imgList: [],
          remark: null,
        },
        titleName: '',
        batchImportVisible: false,
        batchImportForm: {
          fileName: '',
          filePath: '',
          file: '',
          customizationData: {
            time: moment().locale('zh-cn').format('YYYYMMDDHHmmss')
          },
          saveList: []
        },
        headers: {
          'Authorization': getToken()
        },
        fileList: [],
        url: localStorage.getItem('GATEWAY'),
        isExcel: false
      }
    },
    created() {
      this.orderGetInitList()
    },
    methods: {
      orderApiGetList,
      // 下载模板
      downExcelTemp(fileUrl) {
        location.href = "../../static/template/" + fileUrl;
      },
      //批量导入
      batchImport() {
        this.batchImportVisible = true;
        this.batchImportForm.fileName = '';
        this.batchImportForm.file = '';
        this.batchImportForm.saveList = [];
      },
      uploadExcel() {
        this.isExcel = true;
        this.$refs.uploadFile.submit();
      },
      onSuccess() {
        this.isExcel = false;
        this.batchImportVisible = false;
        this.$notify({title: "导入", message: '导入成功', position: 'bottom-right', type: 'success'});
      },
      fileChange(file, fileList) {
        this.batchImportForm.file = file.raw;
        this.batchImportForm.fileName = file.name;
        if (file.status == 'ready') {
          const Xls = file.name.split('.');
          if (Xls[1] === 'xls' || Xls[1] === 'xlsx') {
            return file;
          } else {
            this.$notify({title: "上传文件", message: '文件格式不正确', position: 'bottom-right', type: 'warning'});
            this.batchImportForm.fileName = '';
            this.batchImportForm.file = '';
            return false
          }
        }
      },
      beforeAvatarUpload(file) {
        const Xls = file.name.split('.');
        if (Xls[1] === 'xls' || Xls[1] === 'xlsx') {
          return file;
        } else {
          this.$notify({title: "上传文件", message: '文件格式不正确', position: 'bottom-right', type: 'warning'});
          this.batchImportForm.fileName = '';
          return false
        }
      },
      //导出
      exportExcel() {
        let self = this;
        download(`api/price-library/export`).then(res => {
          downloadFile(res.data, res.headers.downloadFileName, 'xlsx')
        })
      },
      queryList: function () {
        let self = this;
        if (!self.startCode || !self.destinationCode) {
          self.$notify({
            title: '价格查询',
            message: '请选择出发地和目的地',
            position: 'bottom-right',
            type: 'warning'
          });
          return
        }
        self.showDetailed = true;
        self.$nextTick(() => {
          self.$refs['detailed'].searchTable();
        });
        // self.orderGetInitList()
      },
      //获取提车费用
      getPickCost(row) {
        let self = this;
        console.log(row)
        if (row.pickType && row.pickAreaCode) {
          api.getPickFee({
            areaCode: row.pickAreaCode,
            pickCarType: row.pickType
          }).then(res => {
            if (row.pickFee) {
              if (row.pickFee != res.data) {
                let fee = Number(res.data) - Number(row.pickFee)
                //计算参考价格
                row.totalFee = Number(row.totalFee) + Number(fee)
                row.pickFee = res.data;
              }
            } else {
              row.pickFee = res.data;
              row.totalFee = Number(row.totalFee) + Number(res.data)
            }
            self.$refs.order.$refs.table.doLayout();
          })
        } else {
          if (row.pickFee) {
            row.totalFee = Number(row.totalFee) - Number(row.pickFee)
          }
          row.pickFee = null
          self.$refs.order.$refs.table.doLayout();
        }
      },
      //获取送车费用
      getTakeCost(row) {
        let self = this;
        if (row.takeType && row.takeAreaCode) {
          api.getTakeFee({
            areaCode: row.takeAreaCode,
            takeCarType: row.takeType
          }).then(res => {
            if (row.takeFee) {
              if (row.takeFee != res.data) {
                let fee = Number(res.data) - Number(row.takeFee)
                //计算参考价格
                row.totalFee = Number(row.totalFee) + Number(fee)
                row.takeFee = res.data;
              }
            } else {
              row.takeFee = res.data;
              row.totalFee = Number(row.totalFee) + Number(res.data)
            }
            self.$refs.order.$refs.table.doLayout();
          })
        } else {
          if (row.takeFee) {
            row.totalFee = Number(row.totalFee) - Number(row.takeFee)
          }
          row.takeFee = null
          self.$refs.order.$refs.table.doLayout();
        }
      },
      //添加
      addPrice() {
        let self = this;
        self.titleName = '添加价格';
        self.orderAdd()
      },
      //修改
      openOrderAdder() {
        let self = this;
        self.titleName = '修改价格';
        setTimeout(() => self.orderEdit())
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>